import { Component,game } from "cc";
import { Timer } from "./Timer";
import { StringUtil } from "../../utils/StringUtil";

export class TimerManager extends Component{
    //倒计时数据
    private times:any  = {}
    //服务器时间
    private data_s:Date = new Date();
    //服务器初始时间
    private data_s_start:Date = new Date();
    //服务器修正后时间
    private polymeric_s:number = 0;
    //客户端时间
    private date_c:Date = new Date();

    protected update(dt: number) {
        for (const key  in this.times) {
            let data = this.times[key];
            let timer = data.timer as Timer;
            if (timer.update(dt)) {
                if (data.object[data.filed] > 0) {
                    data.object[data.field]--;
                }

                if(data.object[data.filed] == 0){
                    this.onTimerComplete(data)
                }else if(data.onSecond){
                    data.onSecond.call(data.object);
                }
            }

        }
    }

    private onTimerComplete(data:any){
        if (data.onComplete) {
            data.onComplete.call(data.object);
        }

        if (data.event) {
            this.node.dispatchEvent(data.event);
        }

        delete this.times[data.id]
    }

    //注册一个倒计时器
    public register(object:any,field:string,onSecond:Function,onComplete:Function):string{
        const timer = new Timer();
        timer.setp = 1;
        let data:any  = {}

        data.id = StringUtil.guid();
        data.timer = timer;
        data.object = object;
        data.field = field;
        data.onSecond = onSecond;
        data.onComplete = onComplete;
        this.times[data.id] =data;
        return data.id;
    }
    //注销一个计时器
    public unregister(id:string):void{
        if (this.times[id]) {
            delete this.times[id];
        }
    }

    // TODO: 添加服务器时间同步模块
    /** 获取游戏开始到现在逝去的时间 */
    getTime(): number {
        return game.totalTime;
    }
    /** 游戏最大化时回复时间数据 */
    load(): void {
        for (let key in this.times) {
            let interval = Math.floor((this.getTime() - (this.times[key].startTime || this.getTime())) / 1000);
            let data = this.times[key];
            data.object[data.field] = data.object[data.field] - interval;
            if (data.object[data.field] <= 0) {
                data.object[data.field] = 0;
                this.onTimerComplete(data);
            }
            else {
                this.times[key].startTime = null;
            }
        }
    }
            /** 游戏最小化时记录时间数据 */
    save(): void {
        for (let key in this.times) {
            this.times[key].startTime = this.getTime();
        }
    }

}